package com.zeei.bfs.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSON;
import com.zeei.bfs.service.FileInfoService;
import com.zeei.bfs.vo.FileInfoVO;
import com.zeei.common.controller.BasicController;

/**
 * ClassName: FileUpController Function: 文件上传 FUNCTION. date: 2016年12月22日
 * 下午7:51:58
 *
 * @author DingXiangGuang
 * @since JDK 1.8
 */
@Controller
@RequestMapping("/bfs/fileup")
public class FileUpController extends BasicController {
	private static final Log logger = LogFactory.getLog(FileUpController.class);

	@Autowired
	private FileInfoService fileInfoService;

	@ResponseBody
	@RequestMapping(value = "/uploadfile", method = RequestMethod.POST)
	public void uploadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		PrintWriter writer = null;
		String orgfilename = "";
		// 判断路径状态
		String pathState = request.getParameter("pathState");
		String path = "";
		try {
			Properties pro = new Properties();
			pro.load(FileUpController.class.getResourceAsStream("/file.properties"));
			DiskFileItemFactory factory = new DiskFileItemFactory();
			String filepath = pro.getProperty("path");
			if (pathState != null && "1".equals(pathState)) {
				path = request.getSession().getServletContext().getRealPath("/") + filepath;
			} else {
				path = filepath;
			}
			factory.setRepository(new File(path));
			factory.setSizeThreshold(1024 * 1024);

			// 解析器解析request的上下文
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
			// 先判断request中是否包涵multipart类型的数据，
			if (multipartResolver.isMultipart(request)) {
				// 再将request中的数据转化成multipart类型的数据
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				@SuppressWarnings("rawtypes")
				Iterator iter = multiRequest.getFileNames();

				while (iter.hasNext()) {
					MultipartFile file = multiRequest.getFile((String) iter.next());
					if (file != null) {
						orgfilename = file.getOriginalFilename();
						String extname = orgfilename.substring(orgfilename.lastIndexOf(".") + 1, orgfilename.length());
						String fileName = UUID.randomUUID().toString().replaceAll("-", "");
						String serverfilename = fileName + "." + extname;
						File headPath = new File(path);// 获取文件夹路径
						if (!headPath.exists()) {// 判断文件夹是否创建，没有创建则创建新文件夹
							headPath.mkdirs();
						}
						OutputStream out = new FileOutputStream(new File(path, serverfilename));
						InputStream in = file.getInputStream();
						int filesize = in.available();
						int length = 0;
						byte[] buf = new byte[1024];
						while ((length = in.read(buf)) != -1) {
							out.write(buf, 0, length);
						}
						in.close();
						out.close();
						/** 将上传处理后的数据返回 **/
						map.put("orgfilename", orgfilename);
						map.put("filepath", (filepath + "\\" + serverfilename));

						FileInfoVO fiv = new FileInfoVO();
						fiv.setOrgfilename(orgfilename);
						fiv.setServerfilename(serverfilename);
						fiv.setFilepath(filepath + "\\" + serverfilename);
						fiv.setFilesize(new Double(filesize));
						fiv.setExtname(extname);
						fiv.setCtime(new Date());
						fileInfoService.insertSelective(fiv);
						map.put("fileid", fiv.getFileid());
						map.put("success", "true");
						break;
					}
				}
			}
			response.setContentType("text/xml; charset=UTF-8");
			response.setHeader("Cache-Control", "no-cache");
			response.setHeader("Pragma", "no-cache");
			writer = this.response.getWriter();
			String msg = JSON.toJSONString(map);
			writer.print(msg);

		} catch (Exception e) {
			logger.error("上传文件出错：" + e);
			map.put("success", "false");
			map.put("orgfilename", orgfilename);
			map.put("filepath", path);
			map.put("error", e.getMessage());
			String msg = JSON.toJSONString(map);
			if (writer == null) {
				writer = this.response.getWriter();
			}
			writer.print(msg);
		} finally {
			if (writer != null) {
				writer.close();
			}
		}
	}

	@ResponseBody
	@RequestMapping(value = "/uploadfile1", method = RequestMethod.POST)
	public void uploadFile1() throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String path = "";
		PrintWriter writer = null;
		String orgfilename = "";
		// 判断路径状态
		String pathState = request.getParameter("pathState");
		try {
			Properties pro = new Properties();
			pro.load(FileUpController.class.getResourceAsStream("/file.properties"));
			DiskFileItemFactory factory = new DiskFileItemFactory();
			String filepath = pro.getProperty("path");
			if (pathState != null && "1".equals(pathState)) {
				path = request.getSession().getServletContext().getRealPath("/") + filepath;
			} else {
				path = filepath;
			}
			// path = request.getSession().getServletContext().getRealPath("/")
			// + filepath;
			factory.setRepository(new File(path));
			factory.setSizeThreshold(1024 * 1024);
			ServletFileUpload upload = new ServletFileUpload(factory);
			// try {
			// 可以上传多个文件
			List<FileItem> list = upload.parseRequest(request);
			for (FileItem item : list) {
				if (!item.isFormField()) {
					orgfilename = item.getName();
					String extname = orgfilename.substring(orgfilename.lastIndexOf(".") + 1, orgfilename.length());
					String fileName = UUID.randomUUID().toString().replaceAll("-", "");
					System.out.println(fileName);
					String serverfilename = fileName + "." + extname;
					File headPath = new File(path);// 获取文件夹路径
					if (!headPath.exists()) {// 判断文件夹是否创建，没有创建则创建新文件夹
						headPath.mkdirs();
					}
					OutputStream out = new FileOutputStream(new File(path, serverfilename));
					InputStream in = item.getInputStream();
					int filesize = in.available();
					int length = 0;
					byte[] buf = new byte[1024];
					while ((length = in.read(buf)) != -1) {
						out.write(buf, 0, length);
					}
					in.close();
					out.close();
					/** 将上传处理后的数据返回 **/
					map.put("orgfilename", orgfilename);
					map.put("filepath", (filepath + "\\" + serverfilename));

					FileInfoVO fiv = new FileInfoVO();
					fiv.setOrgfilename(orgfilename);
					fiv.setServerfilename(serverfilename);
					fiv.setFilepath(filepath + "\\" + serverfilename);
					fiv.setFilesize(new Double(filesize));
					fiv.setExtname(extname);
					fiv.setCtime(new Date());
					fileInfoService.insertSelective(fiv);
					map.put("fileid", fiv.getFileid());
					map.put("success", "true");
					// HttpRequestUtil.sendPost(strURL, param);
					break;
				}
			}

			response.setContentType("text/xml; charset=UTF-8");
			response.setHeader("Cache-Control", "no-cache");
			response.setHeader("Pragma", "no-cache");
			writer = this.response.getWriter();
			String msg = JSON.toJSONString(map);
			writer.print(msg);

		} catch (Exception e) {
			logger.error("上传文件出错：" + e);
			map.put("success", "false");
			map.put("orgfilename", orgfilename);
			map.put("filepath", path);
			map.put("error", e.getMessage());
			String msg = JSON.toJSONString(map);
			if (writer == null) {
				writer = this.response.getWriter();
			}
			writer.print(msg);
		} finally {
			if (writer != null) {
				writer.close();
			}
		}
	}

	/**
	 * 
	 * appUploadFile:APP文件上传
	 * 
	 * @param files
	 *            上传文件裂变
	 * @param data
	 *            预留data数据
	 * @throws Exception
	 *             void
	 * 
	 *             追加时间：2017年10月23日14:13:14 追加人：DingXiangGuang
	 */
	@ResponseBody
	@SuppressWarnings("unused")
	@RequestMapping(value = "/appuploadfile", method = RequestMethod.POST)
	public void appUploadFile(@RequestParam("files") MultipartFile[] files) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String path = "";
		PrintWriter writer = null;
		String orgfilename = "";

		try {
			Properties pro = new Properties();
			pro.load(FileUpController.class.getResourceAsStream("/file.properties"));
			DiskFileItemFactory factory = new DiskFileItemFactory();
			String filepath = pro.getProperty("apppath");
			path = request.getSession().getServletContext().getRealPath("/") + filepath;
			factory.setRepository(new File(path));
			factory.setSizeThreshold(1024 * 1024);
			for (Integer i = 0; i < files.length; i++) {
				orgfilename = files[i].getOriginalFilename(); // 传入名称
				String extname = orgfilename.substring(orgfilename.lastIndexOf(".") + 1, orgfilename.length()); // 图片后缀
				String fileName = UUID.randomUUID().toString().replaceAll("-", ""); // 图片当前名称
				String serverfilename = fileName + "." + extname; // 服务器保存的图片名称
				File headPath = new File(path);// 获取文件夹路径
				if (!headPath.exists()) {// 判断文件夹是否创建，没有创建则创建新文件夹
					headPath.mkdirs();
				}
				OutputStream out = new FileOutputStream(new File(path, serverfilename));
				InputStream in = files[i].getInputStream();
				int filesize = in.available();
				int length = 0;
				byte[] buf = new byte[1024];
				while ((length = in.read(buf)) != -1) {
					out.write(buf, 0, length);
				}
				in.close();
				out.close();
				/** 将上传处理后的数据返回 **/
				map.put("orgfilename", orgfilename);
				map.put("filepath", (filepath + "\\" + serverfilename));

				FileInfoVO fiv = new FileInfoVO();
				fiv.setOrgfilename(orgfilename);
				fiv.setServerfilename(serverfilename);
				fiv.setFilepath(filepath + "\\" + serverfilename);
				fiv.setFilesize(new Double(filesize));
				fiv.setExtname(extname);
				fiv.setCtime(new Date());
				fileInfoService.insertSelective(fiv);
				map.put("fileid", fiv.getFileid());
				map.put("success", "true");
				break;
			}
			response.setContentType("text/xml; charset=UTF-8");
			response.setHeader("Cache-Control", "no-cache");
			response.setHeader("Pragma", "no-cache");
			writer = this.response.getWriter();
			String msg = JSON.toJSONString(map);
			writer.print(msg);

		} catch (Exception e) {
			logger.error("上传文件出错：" + e);
			map.put("success", "false");
			map.put("orgfilename", orgfilename);
			map.put("filepath", path);
			map.put("error", e.getMessage());
			String msg = JSON.toJSONString(map);
			if (writer == null) {
				writer = this.response.getWriter();
			}
			writer.print(msg);
		} finally {
			if (writer != null) {
				writer.close();
			}
		}
	}

}